{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 第1节：数据的CSV文件存取\n",
    "### CSV文件简介\n",
    "CSV (Comma‐Separated Value, 逗号分隔值文件)\n",
    "\n",
    "**例如**：源数据及其CSV格式\n",
    "![avatar](./image/day2-img1.PNG)\n",
    "![avatar](./image/day2-img2.PNG)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "### 存入数据至CSV中（也可以是其他文件格式）\n",
    "\n",
    "np.savetxt(frame, array, fmt='%.18e', delimiter=None)\n",
    "\n",
    "+ frame : 文件、字符串或产生器，可以是.gz或.bz2的压缩文件\n",
    "+ array : 存入文件的数组\n",
    "+ fmt : 写入文件的格式，例如：%d %.2f %.18e\n",
    "+ delimiter : 分割字符串，默认是任何空格\n",
    "\n",
    "### 从CSV文件中读取数据\n",
    "\n",
    "np.loadtxt(frame, dtype=np.float, delimiter=None， unpack=False)\n",
    "\n",
    "+ frame : 文件、字符串或产生器，可以是.gz或.bz2的压缩文件\n",
    "+ dtype : 数据类型，可选\n",
    "+ delimiter : 分割字符串，默认是任何空格\n",
    "+ unpack :False，即将数据逐行输出，当设置为True时，数据将逐列输出"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "a = np.arange(100).reshape(5, 20)\n",
    "np.savetxt('a.csv', a, fmt=\"%d\", delimiter=',')\n",
    "\n",
    "# np.savetxt('a.csv', a, fmt=\"%.2f\", delimiter=',')#保留2位小数"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "**可以看到已经生成了一个CSV文件**\n",
    "![avatar](./image/day2-img3.PNG)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19]\n",
      " [20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39]\n",
      " [40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59]\n",
      " [60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79]\n",
      " [80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99]]\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "array([[ 0, 20, 40, 60, 80],\n",
       "       [ 1, 21, 41, 61, 81],\n",
       "       [ 2, 22, 42, 62, 82],\n",
       "       [ 3, 23, 43, 63, 83],\n",
       "       [ 4, 24, 44, 64, 84],\n",
       "       [ 5, 25, 45, 65, 85],\n",
       "       [ 6, 26, 46, 66, 86],\n",
       "       [ 7, 27, 47, 67, 87],\n",
       "       [ 8, 28, 48, 68, 88],\n",
       "       [ 9, 29, 49, 69, 89],\n",
       "       [10, 30, 50, 70, 90],\n",
       "       [11, 31, 51, 71, 91],\n",
       "       [12, 32, 52, 72, 92],\n",
       "       [13, 33, 53, 73, 93],\n",
       "       [14, 34, 54, 74, 94],\n",
       "       [15, 35, 55, 75, 95],\n",
       "       [16, 36, 56, 76, 96],\n",
       "       [17, 37, 57, 77, 97],\n",
       "       [18, 38, 58, 78, 98],\n",
       "       [19, 39, 59, 79, 99]])"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "b = np.loadtxt('a.csv', dtype=np.int32, delimiter=',', unpack=False)\n",
    "print(b)\n",
    "# 注意unpack参数的区别\n",
    "b = np.loadtxt('a.csv', dtype=np.int32, delimiter=',', unpack=True)\n",
    "b"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "----\n",
    "**局限**\n",
    "+ CSV只能有效存储一维和二维数组\n",
    "+ np.savetxt() np.loadtxt()只能有效存取一维和二维数组"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "----\n",
    "# 第2节：多维数据的存取\n",
    "+ a.tofile()方法\n",
    "+ np.fromfile()方法"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "# a.tofile(frame, sep='', format='%s')\n",
    "# frame：文件名\n",
    "# seg：分隔符，一般使用‘，’。如果sep是空串，则默认储存为二进制文件\n",
    "# format：写入文件的格式\n",
    "\n",
    "a = np.arange(100).reshape(5, 10, 2)\n",
    "\n",
    "a.tofile(\"b.dat\", sep=',', format='%d') #以数字存放\n",
    "a.tofile(\"c.dat\",sep='',format='%d') #存为二进制文件，复杂的二进制编码"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16,\n",
       "       17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33,\n",
       "       34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50,\n",
       "       51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67,\n",
       "       68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84,\n",
       "       85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99])"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# np.fromfile(frame, dtype=float, count=‐1, sep='')\n",
    "\n",
    "# frame：文件名\n",
    "# dtype：数据类型\n",
    "# count：读取数据的个数。-1表示全部读入\n",
    "# seg: 数据分割字符串，如果是空串，写入文件为二进制\n",
    "c = np.fromfile('b.dat', dtype=np.int32, count=-1, sep=',')\n",
    "c"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16,\n",
       "       17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33,\n",
       "       34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50,\n",
       "       51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67,\n",
       "       68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84,\n",
       "       85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99])"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "d = np.fromfile('c.dat', dtype=np.int32, count=-1, sep='') #从二进制读取\n",
    "d\n",
    "# 必须知道原来数据的维度才可以还原\n",
    "# 该方法需要读取时知道存入文件时数组的维度和元素类型\n",
    "# 可以通过元数据文件（建立一个文件，专门存放维度信息、类型）来存储额外信息"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[[ 0,  1],\n",
       "        [ 2,  3],\n",
       "        [ 4,  5],\n",
       "        [ 6,  7],\n",
       "        [ 8,  9],\n",
       "        [10, 11],\n",
       "        [12, 13],\n",
       "        [14, 15],\n",
       "        [16, 17],\n",
       "        [18, 19]],\n",
       "\n",
       "       [[20, 21],\n",
       "        [22, 23],\n",
       "        [24, 25],\n",
       "        [26, 27],\n",
       "        [28, 29],\n",
       "        [30, 31],\n",
       "        [32, 33],\n",
       "        [34, 35],\n",
       "        [36, 37],\n",
       "        [38, 39]],\n",
       "\n",
       "       [[40, 41],\n",
       "        [42, 43],\n",
       "        [44, 45],\n",
       "        [46, 47],\n",
       "        [48, 49],\n",
       "        [50, 51],\n",
       "        [52, 53],\n",
       "        [54, 55],\n",
       "        [56, 57],\n",
       "        [58, 59]],\n",
       "\n",
       "       [[60, 61],\n",
       "        [62, 63],\n",
       "        [64, 65],\n",
       "        [66, 67],\n",
       "        [68, 69],\n",
       "        [70, 71],\n",
       "        [72, 73],\n",
       "        [74, 75],\n",
       "        [76, 77],\n",
       "        [78, 79]],\n",
       "\n",
       "       [[80, 81],\n",
       "        [82, 83],\n",
       "        [84, 85],\n",
       "        [86, 87],\n",
       "        [88, 89],\n",
       "        [90, 91],\n",
       "        [92, 93],\n",
       "        [94, 95],\n",
       "        [96, 97],\n",
       "        [98, 99]]])"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# NumPy快捷数据存取\n",
    "# np.save(fname, array) #拓展名.npy\n",
    "# np.savez(fname, array) #存取为压缩文件.npyz\n",
    "# np.load(fname)\n",
    "\n",
    "a = np.arange(100).reshape(5, 10, 2)\n",
    "np.save('a.npy', a)\n",
    "b = np.load('a.npy')\n",
    "b\n",
    "# .npy文件中储存了数据的类型、维度等基本信息"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "# 第3节：NumPy随机数函数\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(0.20780454119874414, 1.8997910743962043, 2)"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Python自带的随机数复习\n",
    "import random\n",
    "\n",
    "a = random.random()  # 随机生成一个 [0,1) 的浮点数\n",
    "b = random.uniform(1, 2)  # 随机生成一个 [a,b) 的浮点数\n",
    "c = random.randint(1, 3)  # 随机生成一个 [a,b] 的整数\n",
    "a,b,c"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(array([[0.28655304, 0.17702409, 0.9277644 ],\n",
       "        [0.70396259, 0.40298429, 0.87453533]]),\n",
       " array([[-0.23375802,  1.51635497,  0.75664759],\n",
       "        [-0.43996581,  0.63096035,  0.98091583]]))"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# NumPy随机数函数1\n",
    "\n",
    "# rand(d0,d1,..,dn)\n",
    "# 根据维度(d0‐dn)创建随机数数组，[0,1)的浮点数，均匀分布\n",
    "a = np.random.rand(2, 3)\n",
    "\n",
    "# randn(d0,d1,..,dn)\n",
    "# 根据维度(d0‐dn)创建随机数数组，服从标准正态分布\n",
    "b = np.random.randn(2, 3)\n",
    "\n",
    "a,b"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(array([[ 0,  4,  3],\n",
       "        [-1,  0,  2]]),\n",
       " array([[ 0,  4,  3],\n",
       "        [-1,  0,  2]]),\n",
       " array([[ 3,  0,  4],\n",
       "        [-1,  4,  0]]))"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# randint(low,high,shape)\n",
    "# 根据shape创建随机整数或整数数组，范围是[low, high)\n",
    "# .seed设置随机数种子，一个随机数种子对应一种随机数情况\n",
    "\n",
    "np.random.seed(10)\n",
    "a = np.random.randint(-1, 5, (2, 3))\n",
    "\n",
    "np.random.seed(10)\n",
    "b = np.random.randint(-1, 5, (2, 3))\n",
    "\n",
    "c = np.random.randint(-1, 5, (2, 3))\n",
    "\n",
    "a,b,c#可见a和b的随机种子都是10，他们的结果一样，而c不一样"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[6, 7],\n",
       "       [2, 3],\n",
       "       [0, 1],\n",
       "       [4, 5]])"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# NumPy随机数函数2\n",
    "\n",
    "# shuffle(a) 根据数组a的第1维度进行随排列，改变原数组\n",
    "\n",
    "# permutation(a) 根据数组a的第1维度产生一个新的乱序数组，不改变原数组\n",
    "\n",
    "a = np.arange(8).reshape(4, 2)\n",
    "np.random.shuffle(a)\n",
    "a\n",
    "\n",
    "# 只对<第一维>进行打乱顺序，<第一维中>的顺序并不会打乱\n",
    "\n",
    "'''\n",
    "原理：a = [\n",
    "    [0,1],\n",
    "    [2,3],\n",
    "    [4,5],\n",
    "    [6,7]\n",
    "]\n",
    "进行随机排列\n",
    "获得\n",
    "    [6, 7],\n",
    "    [2, 3],\n",
    "    [0, 1],\n",
    "    [4, 5]\n",
    "'''"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(array([[0, 1],\n",
       "        [2, 3],\n",
       "        [4, 5],\n",
       "        [6, 7]]),\n",
       " array([[2, 3],\n",
       "        [6, 7],\n",
       "        [0, 1],\n",
       "        [4, 5]]))"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a = np.arange(8).reshape(4,2)\n",
    "b = np.random.permutation(a)\n",
    "a,b #原理一致，但是 a 不变"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(array([[5, 2],\n",
       "        [1, 8],\n",
       "        [7, 6]]),\n",
       " array([[2, 4],\n",
       "        [7, 6],\n",
       "        [6, 2]]),\n",
       " array([[7, 9],\n",
       "        [3, 6],\n",
       "        [8, 5]]))"
      ]
     },
     "execution_count": 26,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 从【一维数组a】中以概率 p 抽取元素，形成 shape 形状新数组 replace表示是否可以重用元素，默认为False\n",
    "\n",
    "#np.random.choice(a, size=None, replace=True, p=None)\n",
    "\n",
    "b = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])\n",
    "\n",
    "# replace=True是放回采样，False则为非放回采样\n",
    "\n",
    "x = np.random.choice(b, (3, 2), replace = False)\n",
    "y = np.random.choice(b, (3, 2), replace = True)\n",
    "\n",
    "# p是概率，p的和必须为1，p的每一个元素代表b中对应元素取到的概率\n",
    "# p的大小必须跟b一致\n",
    "z = np.random.choice(b, (3, 2), replace = False,p = b/np.sum(b) )\n",
    "\n",
    "x,y,z # 注意x无重复，y有重复"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(array([[6.27419782, 1.33384972, 4.15590752],\n",
       "        [6.06871616, 3.69756885, 5.61100738]]),\n",
       " array([[-0.92290926,  0.46975143, -0.14436676],\n",
       "        [-0.40013835, -0.29598385,  0.84820861]]),\n",
       " array([[0, 1, 1],\n",
       "        [0, 0, 0]]))"
      ]
     },
     "execution_count": 27,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import numpy as np\n",
    "\n",
    "# uniform(low,high,size) 产生具有均匀分布的数组,low起始值,high结束值,size形状\n",
    "# normal(loc,scale,size) 产生具有正态分布的数组,loc均值,scale标准差,size形状\n",
    "# poisson(lam,size) 产生具有泊松分布的数组,lam随机事件发生率,size形状\n",
    "\n",
    "a = np.random.uniform(1, 10, (2, 3))\n",
    "b = np.random.normal(0, 1, (2, 3))\n",
    "c = np.random.poisson(0.5, (2, 3))\n",
    "\n",
    "a, b, c"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "# 第4节：NumPy统计函数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "a =  [[0 1 2 3]\n",
      " [4 5 6 7]]\n",
      "np.sum(a)默认是a所有元素的和 =  28\n",
      "[ 6 22]\n"
     ]
    }
   ],
   "source": [
    "# sum(a, axis=None) 根据给定轴axis计算数组a相关元素之和，axis整数或元组\n",
    "\n",
    "a = np.arange(8).reshape(2, 4)\n",
    "print(\"a = \",a)\n",
    "print(\"np.sum(a)默认是a所有元素的和 = \",np.sum(a))\n",
    "\n",
    "Sum = np.sum(a, axis = 1)#计算第2维度的和\n",
    "print(Sum)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[0 1 2 3]\n",
      " [4 5 6 7]]\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "array([1.5, 5.5])"
      ]
     },
     "execution_count": 32,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# mean(a, axis=None) 根据给定轴axis计算数组a相关元素的期望，axis整数或元组\n",
    "a = np.arange(8).reshape(2, 4)\n",
    "print(a)\n",
    "np.mean(a, axis=1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "2.1"
      ]
     },
     "execution_count": 33,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# average(a,axis=None,weights=None) 根据给定轴axis计算数组a相关元素的加权平均值\n",
    "a = np.array([1, 2, 3])\n",
    "\n",
    "np.average(a, weights=[0.3, 0.3, 0.4])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(4.320493798938574, 18.666666666666668)"
      ]
     },
     "execution_count": 34,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# std(a, axis=None) 根据给定轴axis计算数组a相关元素的标准差\n",
    "# var(a, axis=None) 根据给定轴axis计算数组a相关元素的方差\n",
    "a = np.arange(15).reshape(3,5)\n",
    "np.std(a),np.var(a)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(5, -6)"
      ]
     },
     "execution_count": 36,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#min(a) max(a) 计算数组a中元素的最小值、最大值\n",
    "#argmin(a) argmax(a) 计算数组a中元素最小值、最大值的下标（不管是一维数组还是多维数组，都给他降成一维数组下标）\n",
    "a = np.array([\n",
    "    [3, 5],\n",
    "    [-6, 1]\n",
    "])\n",
    "\n",
    "np.max(a),np.min(a)#直接获取最大最小值"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "1"
      ]
     },
     "execution_count": 37,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "np.argmax(a) #最大的数下标(0,1)如果把数组a看作一维数组，5的下标就是1\n",
    "#np.argmin(a) 同理 "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(0, 1)"
      ]
     },
     "execution_count": 39,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#unravel_index(index, shape) 根据shape将一维下标index转换成多维下标\n",
    "\n",
    "# 转化为多维下标了\n",
    "\n",
    "np.unravel_index(1,(2,2))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(5, 3.5)"
      ]
     },
     "execution_count": 40,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#ptp(a) 计算数组a中元素最大值与最小值的差\n",
    "#median(a) 计算数组a中元素的中位数（中值）\n",
    "\n",
    "a = np.array([1,2,3,4,5,6])\n",
    "np.ptp(a),np.median(a)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "# 第5讲：梯度函数\n",
    "\n",
    "梯度也叫变化率\n",
    "\n",
    "梯度：连续值之间的变化率，即斜率\n",
    "\n",
    "XY坐标轴连续三个X坐标对应的Y轴值：a, b, c，其中，b的梯度是： (c‐a)/2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 48,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[1, 1.5, 2.5, 2.0, 1]"
      ]
     },
     "execution_count": 48,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import numpy as np\n",
    "\n",
    "# 以一维数组为例\n",
    "a = [1, 2, 4, 7, 8]\n",
    "\n",
    "# 计算方法\n",
    "# 第一个元素1：  梯度 = （第二个元素-第一个元素）/ 1\n",
    "# 最后一个元素8：梯度 = （最后一个元素 - 倒数第二个元素）/ 1\n",
    "# 其他元素(第i个) 梯度 = （a[i+1] - a[i-1]) / 2\n",
    "\n",
    "b = []\n",
    "for i in range(0, len(a)):\n",
    "    if i == 0:\n",
    "        b.append(a[1] - a[0])\n",
    "    elif i == len(a)-1:\n",
    "        b.append(a[-1]-a[-2])\n",
    "    else:\n",
    "        b.append((a[i+1]-a[i-1])/2)\n",
    "\n",
    "b"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 50,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([1. , 1.5, 2.5, 2. , 1. ])"
      ]
     },
     "execution_count": 50,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a = np.array(a)\n",
    "np.gradient(a)\n",
    "#二者是一致的"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 52,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[array([[ -4. ,  -2. ,  -5. , -30. , -17. ],\n",
       "        [  7. ,  -4. ,  -5.5, -12. ,  -2.5],\n",
       "        [ 18. ,  -6. ,  -6. ,   6. ,  12. ]]),\n",
       " array([[ 40. ,   6.5,   1.5,  13. ,  -4. ],\n",
       "        [ 42. ,   6. , -12.5,   7. ,   9. ],\n",
       "        [ 18. ,  -6. ,  -6.5,  16. ,  15. ]])]"
      ]
     },
     "execution_count": 52,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 多维数组的梯度\n",
    "import numpy as np\n",
    "\n",
    "c = np.random.randint(0,50,(3,5))\n",
    "np.gradient(c)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3.8.1 64-bit",
   "language": "python",
   "name": "python38164bitfe2ebe8b9a4f493e93d81a74c550882b"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.1"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
